package com.oreilly.ez.web;


import com.oreilly.ez.base.R;
import com.oreilly.ez.base.WebSocketServer;
import com.oreilly.ez.base.WiselyResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.IOException;
import java.util.Date;

@Controller
@RequestMapping("/wsocket")
public class WebSocketCtrl {

    @Autowired
    private SimpMessagingTemplate simpMessagingTemplate;

//    @RequestMapping("/socket/push/{cid}")
//    public Object pushToWeb(@PathVariable String cid, String message) {
//        try {
//            WebSocketServer.sendInfo(message,cid);
//        } catch (IOException e) {
//            e.printStackTrace();
//            return R.err(cid+"#"+e.getMessage());
//        }
//        return R.ok(cid);
//    }


    /**
     * 接收客户发来的消息, 并推送给 指定的用户
     * app 登录后, 马上得到用户有多少条未读消息
     * 发送给指定用户
     * @param userId
     */
    @MessageMapping("/msg")
    public void handleSubscribe(String userId) {
        System.out.println(userId);

        //未读消息数量 10

        Integer count = 10;
        simpMessagingTemplate.convertAndSendToUser(userId, "/count", count);
    }


    /**
     *
     * @param userId
     * @return
     */
    @MessageMapping("/welcome1")
    public WiselyResponse welcome(String userId) {
        System.out.println(userId);

        //未读消息数量 10
        WiselyResponse response = new WiselyResponse();
        response.setMsg("welcome to China!");
        simpMessagingTemplate.convertAndSendToUser(userId, "/msg", response);

        return response;
    }


    /**
     * 同步服务器时间
     * 广播
     */
    @MessageMapping("/time")  //接收消息的主题
    @SendTo("/topic/time")  //推送消息的主题
    public void sendTime() {

        WiselyResponse response = new WiselyResponse();
        response.setMsg(String.valueOf(new Date().getTime()));
//        simpMessagingTemplate.convertAndSend("/topic/time", new Date().getTime());
        simpMessagingTemplate.convertAndSend("/topic/time", response);
    }



    @MessageMapping("/welcome")
    @SendTo("/topic/getResponse")  //如果服务器接受到了消息，就会对订阅了@SendTo括号中的地址传送消息。
    public WiselyResponse say(String msg ) throws  Exception{

        WiselyResponse response = new WiselyResponse();
        response.setMsg("hello---" + msg);
        simpMessagingTemplate.convertAndSendToUser("67888", "/msg", response);

        return new WiselyResponse("thank you, I get your msg 000000");

//        return null;
    }



}

